<?php

namespace app\index\controller;

use app\common\model\User;
use app\index\validate\UserValidate;
use think\App;
use think\Controller;
use think\Db;
use think\facade\Session;
use think\Request;

class Login extends Controller
{
    protected $userModel;
    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->userModel=new User();
    }

    /** 登录
     * @param Request $request
     * @return mixed|void
     */
    public function index(Request  $request){

        if($request->isPost()){
            $user=$request->post();
            $userValidate = new UserValidate($user);
            if(!$userValidate->check($user)){
                return $this->error($userValidate->getError());
            }
            $userCheck = $this->userModel->login($user);
            if($userCheck->code==0){
                return $this->error($userCheck->msg);
            }
            session("userId",$userCheck->data['id']);
            return $this->success("登陆成功",'/');

        }
        if(\session("userId")){
            return $this->success("已登录",'/');
        }
        return $this->fetch();
    }

    /** 注册
     * @param Request $request
     * @return mixed|void
     */

    public function register(Request  $request){
        if($request->isPost()){
            $user=$request->post();
            $userValidate = new UserValidate($user);
            if(!$userValidate->check($user)){
                return $this->error($userValidate->getError());
            }
            if(session("code")!=$user['code']){
                return $this->error("验证码错误");
            }
            $register = $this->userModel->register($user);
            if($register->code){
                return $this->success($register->msg,"/index/login");
            }
            return $this->error($register->msg);

        }
        return $this->fetch();
    }

    public function layout(){
        Session::clear();
        return $this->success("登出成功","index");
    }
}
